#include "membercardrecharge.h"
#include "ui_membercardrecharge.h"
#include <QDateTime>
#include <QKeyEvent>
#include "mainwindow.h"
#include "calendar.h"
#include "inquiresql.h"
#include "inquirememberprofile.h"
#include <QMessageBox>

#include <QDesktopWidget>

MemberCardRecharge::MemberCardRecharge(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MemberCardRecharge)
{
    ui->setupUi(this);
    this->setLayout(ui->MainLayout);
    this->setFixedSize(487, 508);
    setWindowTitle(tr("会员卡充值"));

    //设置自定义的鼠标指针图案
    QCursor *myCursor= new QCursor(QPixmap(":/Mouse/Image/mouse/mouse.png"),15,10);
    setCursor(*myCursor);

    m_lastClick = -1;
    m_calendar = new Calendar(this);
    m_calendar->hide();
    m_inquireMemberProfile = new InquireMemberProfile;

    QRegExp regExpPrice(" [0-9]{0,6}|[0-9]{0,6}[.]{1}[0-9]{0,2} ");
    QRegExpValidator *pRegExpValidatorPrice = new QRegExpValidator(regExpPrice, this);
    ui->lineEditRechargeAmount->setValidator(pRegExpValidatorPrice);
    ui->lineEditCashPayment->setValidator(pRegExpValidatorPrice);
    ui->lineEditCUPPayment->setValidator(pRegExpValidatorPrice);

    QRegExp regExpIntegrate("[0-9]*");
    QRegExpValidator *pRegExpValidatorIntegrate = new QRegExpValidator(regExpIntegrate, this);
    ui->lineEditRechargeIntegrate->setValidator(pRegExpValidatorIntegrate);

    //匹配所有合理年月日的正则表达式： ^((?!0000)[0-9]{4}-((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31)|([0-9]{2}(0[48]|[2468][048]|[13579][26])|(0[48]|[2468][048]|[13579][26])00)-02-29)$
    QRegExp regExpDate("^((?!0000)[0-9]{4}-((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])"
                            "|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31)|([0-9]{2}(0[48]"
                            "|[2468][048]|[13579][26])|(0[48]|[2468][048]|[13579][26])00)-02-29)$");
    QRegExpValidator *pRegExpValidatorDate = new QRegExpValidator(regExpDate, this);
    ui->lineEditRechargeDate->setValidator(pRegExpValidatorDate);

    ui->lineEditRechargeDate->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd"));

    connect(m_calendar, SIGNAL(signalUpdateLineEditDate(QString)),
            this, SLOT(slotUpdatelineEditRechargeDate(QString)));
    connect(m_inquireMemberProfile, SIGNAL(displayMemberInformation(QString)),
            this, SLOT(slotDisplayMemberInformation(QString)));

    eliminationPushButtonBorder();

    //添加时间过滤器
    ui->lineEditInquireMemberCardNumber->installEventFilter(this);
    ui->pushButtonInquire->installEventFilter(this);
    ui->lineEditRechargeAmount->installEventFilter(this);
    ui->lineEditRechargeIntegrate->installEventFilter(this);
    ui->lineEditCashPayment->installEventFilter(this);
    ui->lineEditCUPPayment->installEventFilter(this);
    ui->comboBoxStaffName->installEventFilter(this);
    ui->lineEditRechargeDate->installEventFilter(this);
    ui->pushButtonRecharge->installEventFilter(this);
}

MemberCardRecharge::~MemberCardRecharge()
{
    delete ui;
}

bool MemberCardRecharge::eventFilter(QObject *target, QEvent *event)
{
    if (target == ui->lineEditRechargeAmount || target == ui->lineEditRechargeIntegrate
            || target == ui->lineEditCashPayment || target == ui->lineEditCUPPayment
            || target == ui->comboBoxStaffName || target == ui->lineEditRechargeDate
            || target == ui->pushButtonRecharge || target == ui->lineEditInquireMemberCardNumber
            || target == ui->pushButtonInquire)
    {
        //鼠标左键按下事件
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                if (target == ui->lineEditInquireMemberCardNumber)
                {
                    if (m_lastClick != lineEditInquireMemberCardNumber){
                        m_lastClick = lineEditInquireMemberCardNumber;
                        ui->lineEditInquireMemberCardNumber->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditInquireMemberCardNumber)
                    {
                        goto flag;
                    }
                }
                if (target == ui->lineEditRechargeAmount)
                {
                    if (m_lastClick != lineEditRechargeAmount){
                        m_lastClick = lineEditRechargeAmount;
                        ui->lineEditRechargeAmount->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditRechargeAmount)
                    {
                        goto flag;
                    }
                }
                if (target == ui->lineEditRechargeIntegrate)
                {
                    if (m_lastClick != lineEditRechargeIntegrate){
                        m_lastClick = lineEditRechargeIntegrate;
                        ui->lineEditRechargeIntegrate->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditRechargeIntegrate)
                    {
                        goto flag;
                    }
                }
                if (target == ui->lineEditCashPayment)
                {
                    if (m_lastClick != lineEditCashRechargePayment){
                        m_lastClick = lineEditCashRechargePayment;
                        if (ui->lineEditRechargeAmount->text() != "0.00")
                        {
                            ui->lineEditCashPayment->setText(
                            completionPrice(QString::number(ui->lineEditRechargeAmount->text().toDouble()
                            - ui->lineEditCUPPayment->text().toDouble())));
                        }
                        ui->lineEditCashPayment->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditCashRechargePayment)
                    {
                        goto flag;
                    }
                }
                if (target == ui->lineEditCUPPayment)
                {
                    if (m_lastClick != lineEditCUPRechargePayment){
                        m_lastClick = lineEditCUPRechargePayment;
                        if (ui->lineEditRechargeAmount->text() != "0.00")
                        {
                            ui->lineEditCUPPayment->setText(
                            completionPrice(QString::number(ui->lineEditRechargeAmount->text().toDouble()
                            - ui->lineEditCashPayment->text().toDouble())));
                        }
                        ui->lineEditCUPPayment->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditCUPRechargePayment)
                    {
                        goto flag;
                    }
                }
                if (target == ui->comboBoxStaffName)
                {
                    m_lastClick = comboBoxRechargeStaffName;
//                    ui->comboBoxStaffName->showPopup();
                }
                if (target == ui->lineEditRechargeDate)
                {
                    if (m_lastClick != lineEditRechargeDate){
                        m_lastClick = lineEditRechargeDate;
                        ui->lineEditRechargeDate->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditRechargeDate)
                    {
                        goto flag;
                    }
                }
                if (target == ui->pushButtonRecharge)
                {
                    m_lastClick = pushButtonRecharge;
                    goto flag;
                }
            }
        }

        //鼠标左键释放事件
        if (event->type() == QEvent::MouseButtonRelease)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                if (target == ui->lineEditRechargeDate)
                {
                    m_calendar->move((QApplication::desktop()->width() - m_calendar->width())/2,
                                     (QApplication::desktop()->height() - m_calendar->height())/2);
                    m_calendar->setSelectedCurrentDate(ui->lineEditRechargeDate->text());
                    m_calendar->setWindowFlags(
                                Qt::Dialog | Qt::FramelessWindowHint);

                    QPoint GlobalPoint(ui->lineEditRechargeDate->mapToGlobal(QPoint(0, 0)));
                    int x = GlobalPoint.x();
                    int y = GlobalPoint.y();
                    m_calendar->setGeometry(x , y + 35, 150, 130);

                    //在对 QWidget 操作时，不能操作其他东西
//                    m_calendar->setWindowModality(Qt::ApplicationModal);
//                    m_calendar->setAttribute(Qt::WA_ShowModal, true);
                    m_calendar->show();
                    goto flag;
                }
            }
        }

        //键盘事件
        if (event->type() == QEvent::KeyPress)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
            if (keyEvent->key() == Qt::Key_Escape)
            {
                this->hide();
                return true;
            }
            if ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))
            {
                if (target == ui->lineEditInquireMemberCardNumber)
                {
                    if (!ui->lineEditInquireMemberCardNumber->text().isEmpty())
                    {
                        HandleLineEditInquireMemberCardNumber();
                        return true;
                    }
                }
                if (target == ui->lineEditRechargeAmount)
                {
                    ui->lineEditRechargeIntegrate->setFocus();
                    ui->lineEditRechargeIntegrate->selectAll();
                    return true;
                }
                if (target == ui->lineEditRechargeIntegrate)
                {
                    ui->lineEditCashPayment->setFocus();
                    ui->lineEditCashPayment->selectAll();
                    return true;
                }
                if (target == ui->lineEditCashPayment)
                {
                    ui->lineEditCUPPayment->setFocus();
                    if (ui->lineEditRechargeAmount->text() != "0.00")
                    {
                        ui->lineEditCUPPayment->setText(
                        completionPrice(QString::number(ui->lineEditRechargeAmount->text().toDouble()
                        - ui->lineEditCashPayment->text().toDouble())));
                    }
                    ui->lineEditCUPPayment->selectAll();
                    return true;
                }
                if (target == ui->lineEditCUPPayment)
                {
                    ui->comboBoxStaffName->setFocus();
                    ui->comboBoxStaffName->showPopup();
                    return true;
                }
                if (target == ui->comboBoxStaffName)
                {
                    ui->lineEditRechargeDate->setFocus();
                    ui->lineEditRechargeDate->selectAll();
                    return true;
                }
                if (target == ui->lineEditRechargeDate)
                {
                    ui->pushButtonRecharge->setFocus();
                    return true;
                }
                if (target == ui->pushButtonRecharge)
                {
                    ui->pushButtonRecharge->setFocus();
                    on_pushButtonRecharge_clicked();
                }
            }
        }
    }
flag:
    return QWidget::eventFilter(target, event);
}

void MemberCardRecharge::set_staffName()
{
    const QStringList staffNameList = m_sql->inquireAllStaffName();
    ui->comboBoxStaffName->clear();
    ui->comboBoxStaffName->addItems(staffNameList);
    QString currentStaffName = m_sql->InquireStaffName(MainWindow::staffID);
    for (int i = 0; i < staffNameList.count(); ++i)
    {
        if (ui->comboBoxStaffName->itemText(i) == currentStaffName)
        {
            ui->comboBoxStaffName->setCurrentIndex(i);
            break;
        }
    }
}

void MemberCardRecharge::on_pushButtonRecharge_clicked()
{
    if (ui->labelMemberCardNumber->text().isEmpty())
    {
        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("\n请先查找出您要充值的会员!") );
        ui->lineEditInquireMemberCardNumber->setFocus();
        ui->lineEditInquireMemberCardNumber->setText(NULL);
        return;
    }
    if (ui->lineEditRechargeAmount->text().toDouble() == 0)
    {
        QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."), tr("\n充值金额不能小于等于零,请核对!") );
        ui->lineEditRechargeAmount->setFocus();
        ui->lineEditRechargeAmount->setText("0.00");
        ui->lineEditRechargeAmount->selectAll();
        return;
    }
    if (!m_sql->UpdatMemberCardAmount(ui->labelMemberCardNumber->text(),
                                      ui->lineEditRechargeAmount->text()))
    {
        QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."), tr("\n会员卡充值失败") );
    }
    if (!m_sql->UpdatStaffMemberRecharge(ui->comboBoxStaffName->currentText(),
                                      ui->lineEditRechargeAmount->text()))
    {
        QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."), tr("\n更新员工业绩失败") );
    }

    PersonMemberOperationDetails memberOperationDetails(
        ui->labelMemberCardNumber->text(), ui->labelMemberName->text(),
        ui->labelMemberLevel->text(), tr("会员充值"),
        ui->lineEditRechargeAmount->text(), ui->lineEditRechargeIntegrate->text(),
        ui->lineEditCashPayment->text(), ui->lineEditCUPPayment->text(),
        ui->comboBoxStaffName->currentText(), ui->lineEditRechargeDate->text());
    if (!m_sql->InsertMemberOperationDetails(memberOperationDetails))
    {
        QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."), tr("\n插入会员操作明细失败") );
        return;
    }
    else
    {
        initRecharge();
        initMemberInformation();
        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("\n会员充值成功") );
    }
}

void MemberCardRecharge::slotUpdatelineEditRechargeDate(QString date)
{
    ui->lineEditRechargeDate->setText(date);
}

void MemberCardRecharge::on_pushButtonInquire_clicked()
{
    m_inquireMemberProfile->changelineEditInquire(ui->lineEditInquireMemberCardNumber->text());

    m_inquireMemberProfile->setWindowFlags(
                Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::ToolTip );
    QPoint GlobalPoint(ui->pushButtonInquire->mapToGlobal(QPoint(0, 0)));
    int x = GlobalPoint.x();//该控件在窗体中左上角横坐标
    int y = GlobalPoint.y();//该控件在窗体中左上角纵坐标
    m_inquireMemberProfile->setGeometry(x - 650, y + 30, 800, 415);
    //在对 QWidget 操作时，不能操作其他东西
    m_inquireMemberProfile->setWindowModality(Qt::ApplicationModal);
    m_inquireMemberProfile->setAttribute(Qt::WA_ShowModal, true);
    m_inquireMemberProfile->show();
}

void MemberCardRecharge::slotDisplayMemberInformation(QString memberCardNumber)
{
    m_personMember = m_sql->InquireMemberInformation(memberCardNumber);

    ui->labelMemberCardNumber->setText(m_personMember.get_personID());
    ui->labelMemberName->setText(m_personMember.get_personName());
    ui->labelGender->setText(m_personMember.get_personGender());
    ui->labelTel->setText(m_personMember.get_personTel());
    ui->labelHandleDate->setText(m_personMember.get_handleDate());
    ui->labelMemberLevel->setText(m_personMember.get_memberLevel());
    ui->labelDiscount->setText(m_personMember.get_discount());
    ui->labelMemberCardAmount->setText(m_personMember.get_membercardAmount());
    ui->labelTotalConsumption->setText(m_personMember.get_totalSpending());
    ui->labelIntegrate->setText(m_personMember.get_integration());
    ui->labelConsumeTimes->setText(m_personMember.get_consumeTimes());

    ui->lineEditRechargeAmount->setFocus();
    ui->lineEditRechargeAmount->selectAll();
}

void MemberCardRecharge::HandleLineEditInquireMemberCardNumber()
{
    m_memberList.clear();
    m_memberList = m_sql->InquireMemberProfile();

    for(int i = 0; i < m_memberList.count(); ++i)
    {
        if (ui->lineEditInquireMemberCardNumber->text() == m_memberList.at(i).get_personID())
        {
            slotDisplayMemberInformation(ui->lineEditInquireMemberCardNumber->text());
            ui->lineEditRechargeAmount->setFocus();
            ui->lineEditRechargeAmount->selectAll();
            ui->lineEditInquireMemberCardNumber->setText(NULL);
            return;
        }
    }

    on_pushButtonInquire_clicked();
}

void MemberCardRecharge::eliminationPushButtonBorder()
{
    //消除边框
    ui->pushButtonCancel->setFlat(true);
    ui->pushButtonInquire->setFlat(true);
    ui->pushButtonRecharge->setFlat(true);
}

QString MemberCardRecharge::completionPrice(const QString &price)
{
    QString number = price;
    if (number.isEmpty())
    {
        number.append("0.00");
        return number;
    }
    if (number.contains(".", Qt::CaseInsensitive))
    {
        if (number.left(1) == ".")
        {
            number.replace(0, 1, "0.");
            return number;
        }
        if (number.right(1) == ".")
        {
            number.append("00");
            return number;
        }
        if (number.right(2).contains(".", Qt::CaseInsensitive))
        {
            number.append("0");
            return number;
        }
    }
    else
    {
        number.append(".00");
        return number;
    }

    return NULL;
}

void MemberCardRecharge::initRecharge()
{
    ui->lineEditRechargeAmount->setText("0.00");
    ui->lineEditRechargeIntegrate->setText("0");
    ui->lineEditCashPayment->setText("0.00");
    ui->lineEditCUPPayment->setText("0.00");
}

void MemberCardRecharge::initMemberInformation()
{
    ui->labelMemberCardNumber->setText(NULL);
    ui->labelMemberName->setText(NULL);
    ui->labelGender->setText(NULL);
    ui->labelTel->setText(NULL);
    ui->labelHandleDate->setText(NULL);
    ui->labelMemberLevel->setText(NULL);
    ui->labelDiscount->setText(NULL);
    ui->labelMemberCardAmount->setText(NULL);
    ui->labelTotalConsumption->setText(NULL);
    ui->labelIntegrate->setText(NULL);
    ui->labelConsumeTimes->setText(NULL);
}

void MemberCardRecharge::on_lineEditRechargeAmount_editingFinished()
{   
    ui->lineEditRechargeAmount->setText(
                completionPrice(ui->lineEditRechargeAmount->text()));
}

void MemberCardRecharge::on_lineEditCashPayment_editingFinished()
{
    if (ui->lineEditCashPayment->text().toDouble() > ui->lineEditRechargeAmount->text().toDouble())
    {
        ui->lineEditCashPayment->setText(completionPrice(ui->lineEditRechargeAmount->text()));
        ui->lineEditCUPPayment->setText("0.00");
        return;
    }
    else if (ui->lineEditRechargeAmount->text() != "0.00")
    {
        ui->lineEditCashPayment->setText(
                    completionPrice(ui->lineEditCashPayment->text()));
        ui->lineEditCUPPayment->setText(
        completionPrice(QString::number(ui->lineEditRechargeAmount->text().toDouble()
        - ui->lineEditCashPayment->text().toDouble())));
    }

}

void MemberCardRecharge::on_lineEditCUPPayment_editingFinished()
{
    if (ui->lineEditCUPPayment->text().toDouble() > ui->lineEditRechargeAmount->text().toDouble())
    {
        ui->lineEditCUPPayment->setText(completionPrice(ui->lineEditRechargeAmount->text()));
        ui->lineEditCashPayment->setText("0.00");
        return;
    }
    else if (ui->lineEditRechargeAmount->text() != "0.00")
    {
        ui->lineEditCashPayment->setText(
        completionPrice(QString::number(ui->lineEditRechargeAmount->text().toDouble()
        - ui->lineEditCUPPayment->text().toDouble())));
        ui->lineEditCUPPayment->setText(
                    completionPrice(ui->lineEditCUPPayment->text()));
    }
}

void MemberCardRecharge::on_lineEditRechargeIntegrate_editingFinished()
{
    ui->lineEditRechargeIntegrate->setText(QString::number(ui->lineEditRechargeIntegrate->text().toInt()));
}

void MemberCardRecharge::on_lineEditRechargeAmount_textChanged(const QString &arg1)
{
    ui->lineEditCashPayment->setText(completionPrice(arg1));
    ui->lineEditCUPPayment->setText("0.00");
}

void MemberCardRecharge::on_pushButtonCancel_clicked()
{
    this->hide();
}
